#pragma once
#include<string>
#include<list>
#include<memory>

#include"inetaddr.hpp"
#include"log.hpp"
#define CONV(addr) ((struct sockaddr *)(addr))

class UserInterface //用户的接口类
{
public:
    virtual ~UserInterface()=default;
    virtual void SendTo(int sockfd,std::string mesg)=0;
    virtual bool operator==(inetaddr &id)=0;
};

class User :public UserInterface
{
public:
    ~User()
    {
    }
    User(struct sockaddr_in &id):_id(id){}
    void SendTo(int sockfd,std::string mesg) override
    {
        int n=::sendto(sockfd,mesg.c_str(),mesg.size(),0,CONV(_id.sockaddr()),_id.len());
        LOG(DEBUG)<<"sockfd:"<<sockfd<<"mesg:"<<mesg<<"ip:"<<_id.ip()<<"port:"<<_id.port()<<"len:"<<_id.len();
        if(n==-1)
        {
            LOG(ERROR)<<"send to "<<_id.addr()<<" fail";
        }
    }
    bool operator==(inetaddr &id)
    {
        if(_id.ip()==id.ip())
            return true;
        return false;
    }
private:
    inetaddr _id;   //每个用户的IP和PORT
};

class UserManager
{
public:
    UserManager()=default;
    void AddUser(struct sockaddr_in &id)  //新增用户
    {
        inetaddr addr(id);
        //查看用户是否在线
        for(auto &e:_manager)
        {
            if(*e==addr)
            {
                LOG(DEBUG)<<"USER: "<< addr.ip()<<"已存在";
                return;
            }
        }
        _manager.push_back(std::make_shared<User>(id));
        LOG(INFO)<<"USER: "<<addr.ip()<<"add successful";   
    }
    void router(int sockfd,const std::string& mesg)//向所有用户转发信息
    {
        for(auto& e:_manager)
        {
            e->SendTo(sockfd,mesg);
        }
        LOG(INFO)<<"转发完成";
    }

    ~UserManager()=default;
private:
    std::list<std::shared_ptr<UserInterface>> _manager;
};